/**
 * 
 */
package com.redshark.wmm.Bluetooth;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import com.redshark.wmm.Bluetooth.BluetoothConnector.BluetoothSocketWrapper;

/**
 * @author bujcich
 * 
 */
public class Bluetooth {
	private final UUID SERIAL_UUID = UUID
			.fromString("00001101-0000-1000-8000-00805F9B34FB");
	@SuppressWarnings("unused")
	private final String PCB_MAC = "00:06:66:67:71:21";
	@SuppressWarnings("unused")
	private final String EK_MAC = "00:06:66:62:A7:21";

	OutputStream outputStream;
	InputStream inputStream;

	BluetoothSocketWrapper socket;

	boolean connecting;

	public InputStream getInputStream() {
		return inputStream;
	}

	public OutputStream getOutputStream() {
		return outputStream;
	}

	public boolean isConnected() {
		if (socket != null) {
			return socket.isConnected();
		} else {
			return false;
		}
	}

	public void connect(String macAddr) throws IOException {
		BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();


		if (!bluetooth.isEnabled()) {
			return;
		}

		BluetoothDevice btd = bluetooth.getRemoteDevice(macAddr);

		List<UUID> uuids = new ArrayList<UUID>();
		uuids.add(SERIAL_UUID);

		BluetoothConnector connector;

		int count = 0;
		int maxTries = 3;
		while (socket == null || !socket.isConnected()) {
			try {
				connector = new BluetoothConnector(btd, false, bluetooth, uuids);
				socket = connector.connect();

				outputStream = socket.getOutputStream();
				inputStream = socket.getInputStream();

			} catch (IOException e) {
				// handle exception
				if (++count == maxTries)
					throw e;
			}
		}
	}

	public void disconnect() throws IOException, InterruptedException {
		//Gotta null these things, otherwise, SegFault
		inputStream.close();
		inputStream = null;
		
		outputStream.close();
		outputStream = null;
		
		socket.close();
		socket = null;
	}
}
